<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入商品名称" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品标题" prop="tiltle">
        <el-input v-model="queryParams.tiltle" placeholder="请输入商品标题" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="商品编号" prop="productNum">
        <el-input v-model="queryParams.productNum" placeholder="请输入商品编号" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="是否上架" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择是否上架" clearable size="small">
          <el-option v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input v-model="queryParams.brand" placeholder="请输入品牌" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="基础价格" prop="basePrice">
        <el-input v-model="queryParams.basePrice" placeholder="请输入基础价格" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="规格" prop="specifications">
        <el-input v-model="queryParams.specifications" placeholder="请输入规格" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="保质期" prop="shelfLife">
        <el-input v-model="queryParams.shelfLife" placeholder="请输入保质期" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="类别" prop="category">
        <el-select v-model="queryParams.category" placeholder="请选择类别" clearable size="small">
          <el-option v-for="dict in categoryList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="储存方式" prop="storageType">
        <el-select v-model="queryParams.storageType" placeholder="请选择储存方式" clearable size="small">
          <el-option v-for="dict in storageTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="商品新增日期" prop="gmtCreate">
        <el-date-picker clearable size="small" v-model="queryParams.gmtCreate" type="date" value-format="yyyy-MM-dd"
          placeholder="选择商品新增日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="商品修改日期" prop="gmtUpdate">
        <el-date-picker clearable size="small" v-model="queryParams.gmtUpdate" type="date" value-format="yyyy-MM-dd"
          placeholder="选择商品修改日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="商品详情" prop="productDetail">
        <el-input v-model="queryParams.productDetail" placeholder="请输入商品详情" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['youxuan:goods:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['youxuan:goods:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['youxuan:goods:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['youxuan:goods:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="商品标题" align="center" prop="tiltle" />
      <el-table-column label="商品编号" align="center" prop="productNum" />
      <el-table-column label="类别" align="center" prop="category" :formatter="categoryFormat" />
      <el-table-column label="是否上架" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="品牌" align="center" prop="brand" />
      <el-table-column label="基础价格" align="center" prop="basePrice" />
      <el-table-column label="库存" align="center" prop="stock" />
      <el-table-column label="可秒杀库存" align="center" prop="secKillStock" />
      <el-table-column label="秒杀总数量" align="center" prop="secKillTotal" />
      <el-table-column label="标价" align="center" prop="bidPrice" />
      <el-table-column label="规格" align="center" prop="specifications" />
      <el-table-column label="保质期" align="center" prop="shelfLife" />
      <el-table-column label="储存方式" align="center" prop="storageType" :formatter="storageTypeFormat" />
      <el-table-column label="商品新增日期" align="center" prop="gmtCreate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品修改日期" align="center" prop="gmtUpdate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtUpdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['youxuan:goods:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['youxuan:goods:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品标题" prop="tiltle">
          <el-input v-model="form.tiltle" placeholder="请输入商品标题" />
        </el-form-item>
        <el-form-item label="商品图片" prop="productImg">
          <!--  <el-input v-model="form.productImg" placeholder="请输入商品图片" /> -->
          <el-upload accept="image/jpeg,image/png" action="oss-cn-beijing.aliyuncs.com" :auto-upload="true" :limit="5"
            :http-request="uploadPic" :before-upload="beforePicUpload" :file-list="showPicList" list-type="picture-card"
            :on-exceed="exceed" :on-preview="handlePictureCardPreview" :on-remove="handleRemovePic">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="类别" prop="category">
          <el-select v-model="form.category" placeholder="请选择类别">
            <el-option v-for="dict in categoryList" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品编号" prop="productNum">
          <el-input v-model="form.productNum" placeholder="请输入商品编号" />
        </el-form-item>
        <el-form-item label="是否上架">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="parseInt(dict.dictValue)">{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand" placeholder="请输入品牌" />
        </el-form-item>
        <el-form-item label="基础价格" prop="basePrice">
          <el-input v-model="form.basePrice" placeholder="请输入基础价格" />
        </el-form-item>
        <el-form-item label="标价" prop="bidPrice">
          <el-input v-model="form.bidPrice" placeholder="请输入标价" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存" />
        </el-form-item>
        <el-form-item label="可秒杀库存" prop="secKillStock">
          <el-input v-model="form.secKillStock" placeholder="请输入可秒杀库存" />
        </el-form-item>
        <el-form-item label="秒杀总数量" prop="secKillTotal">
          <el-input v-model="form.secKillTotal" placeholder="请输入秒杀总数量" />
        </el-form-item>
        <el-form-item label="规格" prop="specifications">
          <el-input v-model="form.specifications" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="保质期" prop="shelfLife">
          <el-input v-model="form.shelfLife" placeholder="请输入保质期" />
        </el-form-item>
        <el-form-item label="储存方式" prop="storageType">
          <el-select v-model="form.storageType" placeholder="请选择储存方式">
            <el-option v-for="dict in storageTypeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品详情" prop="productDetail">
          <el-upload class="avatar-uploader" accept="image/jpeg,image/png" :http-request="uploadDetail" action="oss-cn-beijing.aliyuncs.com" name="img" :show-file-list="false"
            :on-success="uploadSuccess" :on-error="uploadError" :before-upload="beforePicUpload">
          </el-upload>
          <quill-editor  v-model="form.productDetail"   ref="myQuillEditor"   :options="editorOption"   @change="onEditorChange($event)"
              >
              </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  const toolbarOptions = [
    ['bold', 'italic', 'underline', 'strike'], // toggled buttons
    [{
      'header': 1
    }, {
      'header': 2
    }], // custom button values
    [{
      'list': 'ordered'
    }, {
      'list': 'bullet'
    }],
    [{
      'indent': '-1'
    }, {
      'indent': '+1'
    }], // outdent/indent
    [{
      'direction': 'rtl'
    }], // text direction
    [{
      'size': ['small', false, 'large', 'huge']
    }], // custom dropdown
    [{
      'header': [1, 2, 3, 4, 5, 6, false]
    }],
    [{
      'color': []
    }, {
      'background': []
    }], // dropdown with defaults from theme
    [{
      'font': []
    }],
    [{
      'align': []
    }],
    ['link', 'image'],
    ['clean']

  ]
  import Editor from '@/components/Editor';
  import {
    listGoods,
    getGoods,
    delGoods,
    addGoods,
    updateGoods,
    upload,
    exportGoods,
    queryUploadToken
  } from "@/api/youxuan/goods";
  import {
    listCategory
  } from "@/api/youxuan/category";
  import oss from '../../../utils/oss.js'
  export default {
    name: "Goods",
    components: {
      Editor,
    },
    data() {
      return {
        quillUpdateImg: false,
        editorOption: {
          placeholder: '',
          theme: 'snow', // or 'bubble'
          modules: {
            toolbar: {
              container: toolbarOptions,
              handlers: {
                'image': function(value) {
                  if (value) {
                    // 触发input框选择图片文件
                    document.querySelector('.avatar-uploader input').click()
                  } else {
                    this.quill.format('image', false);
                  }
                }
              }
            }
          }
        },

      showPicList: {},
        picList: [],
        fileList: [],
        fileList_1: [],
        dialogImageUrl: '',
        dialogVisible: false,
        // 遮罩层
        loading: true,
        uploadToken: '',
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 商品管理表格数据
        goodsList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否上架字典
        statusOptions: [],
        // 储存方式字典
        storageTypeOptions: [],
        categoryList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          name: null,
          tiltle: null,
          productNum: null,
          status: null,
          brand: null,
          basePrice: null,
          specifications: null,
          shelfLife: null,
          storageType: null,
          category: null,
          productDetail: null
        },
        detailImg:null,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          name: [{
              required: true,
              message: '请输入商品名称',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 15,
              message: '长度在 1 到 15 个字符',
              trigger: 'blur'
            },
          ],
          tiltle: [{
              required: true,
              message: '请输入商品标题',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 30,
              message: '长度在 1 到 30 个字符',
              trigger: 'blur'
            },
          ],
          category: [{
            required: true,
            message: '请选择类别',
            trigger: 'blur'
          }],
          basePrice: [{
            required: true,
            message: '请输入基础价格',
            trigger: 'blur'
          }],
          bidPrice: [{
            required: true,
            message: '请输入标价',
            trigger: 'blur'
          }],
          stock: [{
            required: true,
            message: '请输入库存',
            trigger: 'blur'
          }],
          secKillStock: [{
            required: true,
            message: '请输入可秒杀库存',
            trigger: 'blur'
          }],
          secKillTotal: [{
            required: true,
            message: '请输入秒杀总数量',
            trigger: 'blur'
          }],
          productDetail: [{
              required: true,
              message: '请输入商品详情',
              trigger: 'blur'
            }

          ]
        }
    };
  },
  created() {
      this.getList();
      this.getDicts("sys_goods_status").then(response => {
        this.statusOptions = response.data;
      });
      this.getDicts("sys_goods_storage").then(response => {

        this.storageTypeOptions = response.data;
      });
      listCategory().then(response => {
        console.log("dic", response.rows);
        this.categoryList = response.rows;
      });
    },
    methods: {
       uploadSuccess(res, file) {
        // res为图片服务器返回的数据
        // 获取富文本组件实例
        let that = this;
        that.msgInfo('上传中...请耐心等待');
        setTimeout(function (){
        	that.detailImg = oss.getFileName();
          that.msgSuccess('上传成功！');
          let quill = that.$refs.myQuillEditor.quill
          // 如果上传成功
            if (that.detailImg != null) {
           // 获取光标所在位置

           let length = quill.getSelection().index;
           // 插入图片 res.url为服务器返回的图片地址
           quill.insertEmbed(length, 'image',that.detailImg)
           // 调整光标到最后
           quill.setSelection(length + 1)
          } else {
           that.$message.error('图片插入失败')
          }
          // loading动画消失
          that.quillUpdateImg = false
        }, 3000);

        },
        // 富文本图片上传失败
        uploadError() {
        // loading动画消失
        this.quillUpdateImg = false
        this.$message.error('图片插入失败')

       },
      onEditorChange({editor, html, text}) {//内容改变事件
       console.log("---内容改变事件---")
       this.content = html
       console.log(html)
       },
      queryToken() {
        queryUploadToken().then(response => {
          if (response.code == 200)
            this.uploadToken = response.data;
        });
      },
      exceed() {
        this.$message.error('上传文件个数超过限制！');
      },
      async uploadPic(option) { //上传OSS
        let that = this;
        oss.setToken(that.uploadToken);
        oss.ossUploadFile(option).then(res => {
          if (res != null) {
            that.picList.push(res.fullUrl);
          }
        });
      },
      async uploadDetail(option) { //上传OSS
        let that = this;
        oss.setToken(that.uploadToken);
        oss.ossUploadFile(option).then(res => {
        });
      },
      beforePicUpload(file) {
        this.imageUrl = '';
        const isLt2M = file.size / 1024 / 1024 < 4;

        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 4MB!');
        }
        return isLt2M;
      },

      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      handleRemovePic(file, fileList) {
        var that = this;
        console.log(file, fileList);
        for (var i = 0; i < that.picList.length; i++) {
          if (that.picList[i] == file.name) {
            that.picList.splice(i, 1);
          }
        }


      },
      /** 查询商品管理列表 */
      getList() {
        this.loading = true;
        listGoods(this.queryParams).then(response => {
          this.goodsList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 是否上架字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 储存方式字典翻译
      storageTypeFormat(row, column) {
        return this.selectDictLabel(this.storageTypeOptions, row.storageType);
      },
      //类别字典翻译
      categoryFormat(row, column) {
        return this.selectCategoryLabel(this.categoryList, row.category);
      },
      selectCategoryLabel(datas, value) {
        var actions = [];
        Object.keys(datas).some((key) => {
          if (datas[key].id == ('' + value)) {
            actions.push(datas[key].name);
            return true;
          }
        })
        return actions.join('');
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          name: null,
          tiltle: null,
          productImg: null,
          productNum: null,
          status: 0,
          brand: null,
          basePrice: null,
          bidPrice: null,
          specifications: null,
          shelfLife: null,
          storageType: null,
          gmtCreate: null,
          gmtUpdate: null,
          category: null,
          productDetail: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.queryToken();
        this.showPicList = [];
        this.picList = [];
        this.reset();
        this.open = true;
        this.title = "添加商品";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.queryToken();
        var that = this;
        that.reset();
        that.showPicList = [];
        var picImgUrls = [];
        that.picList = [];
        var pFile = {};
        const id = row.id || that.ids
        getGoods(id).then(response => {
          if (response.data.productImgString != null && response.data.productImgString != '')
            picImgUrls = response.data.productImgString.split(",");
          that.picList = picImgUrls;

          for (var j = 0; j < picImgUrls.length; j++) {
            pFile.name = picImgUrls[j];
            pFile.url = picImgUrls[j];
            that.showPicList.push(pFile);
            pFile = {};
          }
          that.form = response.data;
          that.open = true;
          that.title = "修改商品";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              this.form.productImg = this.picList;
              updateGoods(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              this.form.productImg = this.picList;
              addGoods(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除商品编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delGoods(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有商品数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportGoods(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      }
    }
  };
</script>
<style>
  .ql-editor.ql-blank,
  .ql-editor {
    height: 350px;
  }
</style>
